import * as React from 'react'
import './index.less'

interface IProps {
    distance?: number
}

interface IState {
    visible: boolean
}

export default class ToTop extends React.Component<IProps, IState> {

    public state = {
        visible: false
    }

    private historyTop: number = 0

    public render(): JSX.Element {
        const { visible } = this.state
        return (
            <div className={`top_btn${visible ? ' visible' : ' hide'}`} onClick={this.handleToTop} />
        )
    }

    public componentDidMount() {
        window.addEventListener('scroll', this.handleScroll)
    }

    public componentWillUnmount() {
        window.removeEventListener('scroll', this.handleScroll)
    }

    private handleScroll = () => {
        const { distance } = this.props
        const top = document.documentElement.scrollTop || document.body.scrollTop
        if (top > (distance || 140)) {
            this.setState({
                visible: true
            })
        } else {
            this.setState({
                visible: false
            })
        }
        if (this.historyTop < top) {
            this.setState({
                visible: false
            })
        }
        this.historyTop = top
    }

    private handleToTop = () => {
        const global: any = window
        if (global.scrollTo) {
            global.scrollTo(0, 0)
        } else {
            global.screenTop = 0
        }
    }
}